package org.example.mqactual.producer;

import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageClientIDSetter;
import org.apache.rocketmq.common.message.MessageQueue;
import org.example.entity.Order;

import java.util.List;

/**
 * 订单编号选择队列，相同的订单号发送到相同的队列
 */
public class QueueProducer {

    public static void main(String[] args) throws Exception{
        DefaultMQProducer producer = new DefaultMQProducer("please_rename_unique_group_name");
        producer.setNamesrvAddr("192.168.254.129:9876");
        producer.start();

        //订单实体
        Order order = new Order();
        order.setOrderId(1);
        order.setStatus(0);
        order.setOrderNo("202212170101");
        System.out.printf("%s%n", sendMsg(producer, order));
        //订单状态发生变更
        order.setStatus(1);
        //重新发送消息
        System.out.printf("%s%n", sendMsg(producer, order));
        producer.shutdown();


    }

    public static SendResult sendMsg(DefaultMQProducer producer, Order order) throws Exception {
        //为了方便查找消息，发送消息的时候用了订单编号key，这样可以通过订单编号查询消息
        Message msg=new Message("test_topic", null, order.getOrderNo(), JSON.toJSONString(order).getBytes());

        return producer.send(msg, new MessageQueueSelector() {
            @Override
            public MessageQueue select(List<MessageQueue> list, Message message, Object o) {
                //根据订单标号的hashCode进行队列选择
                if (list == null || list.isEmpty()) {
                    return null;
                }

                int index = Math.abs(o.hashCode() % list.size());
                return list.get(index<0?0:index);
            }
        },order.getOrderNo());
    }
}
